package com.hdax.dm.utils;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.UUID;

@Component
@Slf4j
public class DistributedLockHandler {

    private final static long LOCK_EXPIRE = 30 * 1000L;//单个业务持有锁的时间30s，防止死锁
    private final static long LOCK_TRY_INTERVAL = 30L;//默认30ms尝试一次
    private final static long LOCK_TRY_TIMEOUT = 20 * 1000L;//默认尝试20s

    private String uuid;

    public String getUuid() {
        return uuid;
    }

    @Autowired
    private RedisTemplate<String, String> template;

    public DistributedLockHandler(){
        this.uuid = UUID.randomUUID().toString()+":"+Thread.currentThread().getId();
    }

    /**
     * 尝试获取全局锁
     *
     * @param lock 锁的名称
     * @return true 获取成功，false获取失败
     */
    public boolean tryLock(Lock lock) {
        return getLock(lock, LOCK_TRY_TIMEOUT, LOCK_TRY_INTERVAL, LOCK_EXPIRE);
    }

    /**
     * 尝试获取全局锁
     *
     * @param lock    锁的名称
     * @param timeout 获取超时时间 单位ms
     * @return true 获取成功，false获取失败
     */
    public boolean tryLock(Lock lock, long timeout) {
        return getLock(lock, timeout, LOCK_TRY_INTERVAL, LOCK_EXPIRE);
    }

    /**
     * 尝试获取全局锁
     *
     * @param lock        锁的名称
     * @param timeout     获取锁的超时时间
     * @param tryInterval 多少毫秒尝试获取一次
     * @return true 获取成功，false获取失败
     */
    public boolean tryLock(Lock lock, long timeout, long tryInterval) {
        return getLock(lock, timeout, tryInterval, LOCK_EXPIRE);
    }

    /**
     * 尝试获取全局锁
     *
     * @param lock           锁的名称
     * @param timeout        获取锁的超时时间
     * @param tryInterval    多少毫秒尝试获取一次
     * @param lockExpireTime 锁的过期
     * @return true 获取成功，false获取失败
     */
    public boolean tryLock(Lock lock, long timeout, long tryInterval, long lockExpireTime) {
        return getLock(lock, timeout, tryInterval, lockExpireTime);
    }


    /**
     * 操作redis获取全局锁
     *
     * @param lock           锁的名称
     * @param timeout        获取的超时时间
     * @param tryInterval    多少ms尝试一次
     * @param lockExpireTime 获取成功后锁的过期时间
     * @return true 获取成功，false获取失败
     */
    public boolean getLock(Lock lock, long timeout, long tryInterval, long lockExpireTime) {
        try {
            if(StrUtil.isEmpty(lock.getName()) || StrUtil.isEmpty(lock.getValue())){
                return false;
            }

            DefaultRedisScript<Boolean> defaultRedisScript = new DefaultRedisScript<>();
            defaultRedisScript.setResultType(Boolean.class);
            defaultRedisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("luas/lock.lua")));
//            Boolean isLock = template.execute(defaultRedisScript, Arrays.asList(lock.getName()), lock.getValue(),String.valueOf(DistributedLockHandler.LOCK_EXPIRE));
            System.out.println(lock.getValue());
            while(!template.execute(defaultRedisScript, Arrays.asList(lock.getName()), lock.getValue(),String.valueOf(DistributedLockHandler.LOCK_EXPIRE))){
                Thread.sleep(tryInterval);
//                if (System.currentTimeMillis() - startTime > timeout) {//尝试超过了设定值之后直接跳出循环
//                    return false;
//                }
            }
//            long startTime = System.currentTimeMillis();
//            ValueOperations<String, String> ops = template.opsForValue();
//            do{
////                if (!template.hasKey(lock.getName())) {
////                    ValueOperations<String, String> ops = template.opsForValue();
////                    isLock = ops.setIfAbsent(lock.getName(), lock.getValue(), lockExpireTime, TimeUnit.MILLISECONDS);
////                } else {//存在锁
////                    log.debug("lock is exist!！！");
////                }
////                if (System.currentTimeMillis() - startTime > timeout) {//尝试超过了设定值之后直接跳出循环
////                    return false;
////                }
//                Thread.sleep(tryInterval);
//            }while (!ops.setIfAbsent(lock.getName(), lock.getValue(), lockExpireTime, TimeUnit.MILLISECONDS)) ;
            //while (template.hasKey(lock.getName()) && !isLock) ;
        } catch (InterruptedException e) {
            log.error(e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 释放锁
     */
    public void releaseLock(Lock lock) {
        DefaultRedisScript<Long> defaultRedisScript = new DefaultRedisScript<>();
        defaultRedisScript.setResultType(Long.class);
        defaultRedisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("luas/unlock.lua")));
        Long isDelete = template.execute(defaultRedisScript, Arrays.asList(lock.getName()), lock.getValue());
//        if(isDelete == null)
//            throw new RuntimeException("释放锁失败");
//        if (!StringUtils.isEmpty(lock.getName()) && StrUtil.equals(lock.getValue(),template.opsForValue().get(lock.getName()))) {
//            template.delete(lock.getName());
//        }
    }

}